package com.hoshiicloud.suppplier.controller;

import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.user.dto.supppiler.*;
import com.hoshiicloud.user.param.supppiler.*;
import com.hoshiicloud.suppplier.feign.IUsersService;
import com.hoshiicloud.suppplier.feign.IdGeneratorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:campchen
 * @Date:Created in 下午 02:16 2019/6/20
 * @PACKAGENAME com.hoshiibuy.suppplier.controller
 * @Description
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/suppplier/storeOrganization")
@Api(value = "店铺供应商", tags = {"店铺供应商聚合服务管理"})
public class StoreOrganizationController {
    @Autowired
    private IUsersService usersService;

    @Autowired
    private IdGeneratorService idGeneratorService;

    /**
     * 新增供应商
     */
    @PostMapping("/addStoreOrganization")
    @ApiOperation(value = "店铺供应商新增")
    // @Transactional(rollbackFor = Exception.class)
    public Response addStoreOrganization(@RequestBody AddStoreOrganizationDTO dto) {
        Response rs;
        /**新增供应商*/
        try {
            rs = usersService.saveStoreOrganization(dto.getStoreOrganizationAddParam());
            if (rs.getData() == null) {
                throw new ServiceException(rs.getMsg());
            }
        } catch (Exception e) {
            log.error("新增供应商" + "[" + e.getMessage() + "]");
            return Response.failed("新增供应商异常" + e.getMessage());
        }
        Long organizationId = Long.parseLong(rs.getData().toString());


        /**新增经营类目*/
        List<StoreOrganizationCategoryDTO> listCategory = new ArrayList<>();
        //获得新增经营品类的所有id
        List<Long> categoryIds = new ArrayList<>();
        dto.getListCategory().forEach(storeOrganizationCategoryAddParam -> {
            StoreOrganizationCategoryDTO storeOrganizationCategoryDTO = null;
            try {
                storeOrganizationCategoryDTO = BeanUtils.covertType(storeOrganizationCategoryAddParam, StoreOrganizationCategoryDTO.class);
            } catch (Exception e) {
                throw new ServiceException(CommonError.error("转换失败"));
            }
            Long id = Long.parseLong(idGeneratorService.queryGeneratorId());
            storeOrganizationCategoryDTO.setId(id);
            listCategory.add(storeOrganizationCategoryDTO);
            categoryIds.add(id);
        });
        try {
            rs = usersService.insertCategory4StoreOrganization(listCategory);
            if (rs.getCode() != 200 || rs.getData() == null) {
                throw new ServiceException(rs.getMsg());
            }
        } catch (Exception e) {
            log.error("新增供应商经营品类异常" + "[" + e.getMessage() + "]");
            return Response.failed("新增供应商经营品类异常" + e.getMessage());
        }



        /**新增附件*/
        List<StoreOrganizationAttachmentDTO> list = new ArrayList<>();
        //获得新增附件的所有id
        List<Long> ids=new ArrayList<>();
        dto.getListAttachment().forEach(
                storeOrganizationAttachmentAddParam -> {
                    StoreOrganizationAttachmentDTO storeOrganizationAttachmentDTO = null;
                    try {
                        storeOrganizationAttachmentDTO = BeanUtils.covertType(storeOrganizationAttachmentAddParam, StoreOrganizationAttachmentDTO.class);
                    } catch (Exception e) {
                        throw new ServiceException(CommonError.error("转换失败"));
                    }
                    Long id=Long.parseLong(idGeneratorService.queryGeneratorId());
                    storeOrganizationAttachmentDTO.setId(id);
                    storeOrganizationAttachmentDTO.setVendorId(organizationId);
                    list.add(storeOrganizationAttachmentDTO);
                    ids.add(id);
                }
        );
        try {
            rs = usersService.insertAttach4StoreOrganization(list);
            if (rs.getCode() != 200 || rs.getData() == null) {
                throw new ServiceException(rs.getMsg());
            }
        } catch (Exception e) {
            log.error("新增供应商附件异常" + "[" + e.getMessage() + "]");
            return Response.failed("新增供应商附件异常" + e.getMessage());
        }

        //如果存在该租户会员获取其id 如不存在则新增并获取其id
        Response<Member> responseM = usersService.getMemberByMobile(dto.getCompanyId(),dto.getAdminMobile());

        if (responseM.getCode()!=200||responseM.getData()==null){
            throw new ServiceException(rs.getMsg());
        }
        //关联租户会员与内部员工所需id
        Long memberId =responseM.getData().getId();

        /**新增系统部*/
        StoreOrganizationDepartmentesAddParam storeOrganizationDepartmentesAddParam = new StoreOrganizationDepartmentesAddParam();
        storeOrganizationDepartmentesAddParam.setParentId(0L);
        storeOrganizationDepartmentesAddParam.setOrganizationId(organizationId);
        storeOrganizationDepartmentesAddParam.setMobile(dto.getAdminMobile());
        storeOrganizationDepartmentesAddParam.setName(dto.getStoreOrganizationAddParam().getName());
        storeOrganizationDepartmentesAddParam.setCharge("超级管理员");
        try {
            rs = usersService.saveStoreOrganizationDepartmentes(storeOrganizationDepartmentesAddParam);
            if (rs.getData() == null) {
                throw new ServiceException(rs.getMsg());
            }
        } catch (Exception e) {
            log.error("新增供应商部门异常" + "[" + e.getMessage() + "]");
            return Response.failed("新增供应商部门异常" + e.getMessage());
        }
        //人员与部门关联
        Long departmentesId = Long.parseLong(rs.getData().toString());


        /**新增店铺供应商系统部人员*/
        StoreOrganizationUsersAddParam storeOrganizationUsersAddParam = new StoreOrganizationUsersAddParam();
        storeOrganizationUsersAddParam.setMemberId(memberId);
        storeOrganizationUsersAddParam.setMobile(dto.getAdminMobile());
        storeOrganizationUsersAddParam.setPosition("超级管理员");
        try {
            rs = usersService.saveStoreOrganizationUsers(storeOrganizationUsersAddParam);
            if (rs.getData() == null) {
                throw new ServiceException(rs.getMsg());
            }
        } catch (Exception e) {
            log.error("新增供应商员工异常" + "[" + e.getMessage() + "]");
            return Response.failed("新增供应商员工异常" + e.getMessage());
        }
        //人员与部门进行关联
        Long userId = Long.parseLong(rs.getData().toString());


        /**新增人员部门关联表*/
        StoreOrganizationDepartmentesUsersAddParam storeOrganizationDepartmentesUsersAddParam = new StoreOrganizationDepartmentesUsersAddParam();
        storeOrganizationDepartmentesUsersAddParam.setCompanyId(dto.getCompanyId());
        storeOrganizationDepartmentesUsersAddParam.setPlatformId(dto.getPlatformId());
        storeOrganizationDepartmentesUsersAddParam.setStoreId(dto.getStoreOrganizationAddParam().getStoreId());
        storeOrganizationDepartmentesUsersAddParam.setDepartmentId(departmentesId);
        storeOrganizationDepartmentesUsersAddParam.setRole("2");
        storeOrganizationDepartmentesUsersAddParam.setEnabled(1);
        storeOrganizationDepartmentesUsersAddParam.setUserId(userId);
        storeOrganizationDepartmentesUsersAddParam.setCreatedBy("系统自动生成");
        try {
            rs = usersService.saveStoreOrganizationDepartmentesUsers(storeOrganizationDepartmentesUsersAddParam);
            if (rs.getData() == null) {
                throw new ServiceException(rs.getMsg());
            }
        } catch (Exception e) {
            log.error("新增供应商部门员工关联表异常" + "[" + e.getMessage() + "]");
            return Response.failed("新增供应商部门员工关联表异常" + e.getMessage());
        }
        return Response.data("新增成功");
    }


    /**
     * 店铺供应商人员新增
     */
    @PostMapping("/saveStoreOrganizationUsers")
    @ApiOperation(value = "新增店铺供应商人员")
    @Transactional(rollbackFor = Exception.class)
    public Response saveStoreOrganizationUsers(@RequestBody AddStoreOrganizationUsersDTO dto) {
        Response rs;
        /**通过电话号码查询member是否存在 存在则返回memberId不存在则新增  店铺id  部门id*/
        try {
            rs = usersService.saveStoreOrganizationUsers(dto.getStoreOrganizationUsersAddParam());
            if (rs.getData() == null) {
                throw new ServiceException(rs.getMsg());
            }
        } catch (Exception e) {
            log.error("新增店铺供应商人员失败" + "[" + e.getMessage() + "]");
            return Response.failed("新增店铺供应商人员失败" + e.getMessage());
        }
        String userId = rs.getData().toString();
        /**添加人员的同时 添加部门人员关联表*/
        //将信息添加到部门 用户关联表。
        StoreOrganizationDepartmentesUsersAddParam storeOrganizationDepartmentesUsersAddParam = new StoreOrganizationDepartmentesUsersAddParam();
        storeOrganizationDepartmentesUsersAddParam.setCompanyId(dto.getCompanyId());
        storeOrganizationDepartmentesUsersAddParam.setPlatformId(dto.getPlatformId());
        storeOrganizationDepartmentesUsersAddParam.setStoreId(dto.getStoreId());
        storeOrganizationDepartmentesUsersAddParam.setDepartmentId(dto.getDepartmentesId());
        storeOrganizationDepartmentesUsersAddParam.setRole("2");
        storeOrganizationDepartmentesUsersAddParam.setEnabled(1);
        storeOrganizationDepartmentesUsersAddParam.setUserId(Long.parseLong(userId));
        storeOrganizationDepartmentesUsersAddParam.setCreatedBy("系统自动生成");
        try {
            rs = usersService.saveStoreOrganizationDepartmentesUsers(storeOrganizationDepartmentesUsersAddParam);
            if (rs.getData() == null) {
                throw new ServiceException(rs.getMsg());
            }
        } catch (Exception e) {
            log.error("新增供应商部门员工关联表异常" + "[" + e.getMessage() + "]");
            return Response.failed("新增供应商部门员工关联表异常" + e.getMessage());
        }
        return Response.data("新增成功");
    }


    /**
     * 分页获取供应商列表
     */
    @PostMapping(value = "/getPage4StoreOrganization")
    @ApiOperation(value = "分页获取店铺供应商列表")
    public Response getPage4StoreOrganization(@RequestParam String pageNumber, @RequestParam String pageSize) {
        Response rs;
        try {
            StoreOrganizationQueryParam storeOrganizationQueryParam = new StoreOrganizationQueryParam();
            storeOrganizationQueryParam.setPageNumber(pageNumber);
            storeOrganizationQueryParam.setPageSize(pageSize);
            rs = usersService.getPage(storeOrganizationQueryParam);
        } catch (Exception e) {
            //log.error("分页获取购物车购物信息列表异常"+"["+e.getMessage()+"]");
            rs = Response.failed("分页获取店铺供应商信息列表" + e.getMessage());
        }
        return rs;
    }

    /**
     * 分页获取供应商列表
     */
    @PostMapping(value = "/getPage4StoreOrganizationByStatus")
    @ApiOperation(value = "根据状态分页获取店铺供应商列表")
    public Response<Page<StoreOrganizationQueryParam>> getPage4StoreOrganizationByStatus(@RequestParam Integer status, @RequestParam String pageNumber, @RequestParam String pageSize) {
        Response<Page<StoreOrganizationQueryParam>> rs;
        try {
            StoreOrganizationQueryParam poQueryParam = new StoreOrganizationQueryParam();
            poQueryParam.setStatus(status);
            poQueryParam.setPageNumber(pageNumber);
            poQueryParam.setPageSize(pageSize);
            rs = usersService.getPage(poQueryParam);
        } catch (Exception e) {
            //log.error("分页获取购物车购物信息列表异常"+"["+e.getMessage()+"]");
            rs = Response.failed("根据状态分页获取店铺供应商列表" + e.getMessage());
        }
        return rs;
    }

    /**
     * 根据id查询供应商详情
     */
    @ApiOperation(value = "根据id查询")
    @ApiParam(name = "id", value = "主键ID", required = true)
    @GetMapping("/{id}")
    public Response selectStoreOrganization(@PathVariable("id") @Valid Long id) {
        return usersService.selectStoreOrganization(id);
    }

    /**
     * 根据id修改供应商审核状态status
     */
    @PutMapping(value = "/storeApproval")
    @ApiOperation(value = "根据id修改店铺供应商审核状态status")
    public Response<StoreOrganizationDTO> updateStatusByStoreOrganizationId(@RequestParam Long id, @RequestParam Integer status) {
        Response response = usersService.storeApproval(id, status);
        if (response.getData() == null || response.getCode() != 200) {
            throw new ServiceException(CommonError.error("更新失败"));
        }
        return response;
    }

    /**
     * 店铺供应商修改
     */
    @PutMapping("/updateStoreOrganization")
    @ApiOperation(value = "修改店铺供应商信息")
    public Response updateStoreOrganization(@RequestBody StoreOrganizationUpdateParam Param) {
        Response response = usersService.update(Param);
        if (response.getData() == null || response.getCode() != 200) {
            throw new ServiceException(CommonError.error("更新失败"));
        }
        return response;
    }

    /**
     * 新增店铺供应商部门
     */
    @PostMapping("/saveStoreOrganizationDepartmentes")
    @ApiOperation(value = "新增店铺供应商部门")
    public Response saveStoreOrganizationDepartmentes(@RequestBody StoreOrganizationDepartmentesAddParam param) {
        if (param.getParentId() == null || param.getParentId() == 0L) {
            throw new ServiceException(CommonError.error("父id不能为空"));
        }
        Response response = usersService.saveStoreOrganizationDepartmentes(param);
        if (response.getData() == null || response.getCode() != 200) {
            throw new ServiceException(CommonError.error("新增店铺供应商部门失败"));
        }
        return response;
    }

    /**
     * 手动添加店铺供应商部门与人员关联表新增
     */
    @PostMapping("/saveStoreOrganizationDepartmentesUsers")
    @ApiOperation(value = "新增权限/新增店铺供应商部门与人员关联表")
    public Response saveStoreOrganizationDepartmentesUsers(@RequestBody StoreOrganizationDepartmentesUsersAddParam param) {
        Response response = usersService.saveStoreOrganizationDepartmentesUsers(param);
        if (response.getData() == null || response.getCode() != 200) {
            throw new ServiceException(CommonError.error("新增店铺供应商部门人员关联表失败"));
        }
        return response;
    }

}
